package com.example.chat.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                                  WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 获取URL参数
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 获取userId和groupId参数
            String userId = servletRequest.getServletRequest().getParameter("userId");
            String groupId = servletRequest.getServletRequest().getParameter("groupId");
            
            if (userId != null) {
                // 将用户ID存储到WebSocket会话属性中
                attributes.put("userId", Long.valueOf(userId));
                
                // 如果是群聊，则保存群组ID
                if (groupId != null) {
                    attributes.put("groupId", Long.valueOf(groupId));
                }
                
                return true;
            }
        }
        
        return false; // 如果没有userId，拒绝连接
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                              WebSocketHandler wsHandler, Exception exception) {
        // 握手后的处理，暂不需要实现
    }
} 